package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.WechatUser;
import com.example.demo.service.UserService;
import com.example.demo.util.HttpUtil;
import com.example.demo.vo.DataView;
import com.example.demo.vo.WechatLoginRequestDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

@RequestMapping(value = "/login")
@RestController
@Slf4j
public class LoginController {
    @Autowired
    private HttpUtil httpUtil;
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/wxLogin",method = RequestMethod.POST)
    public DataView getWxCode(@RequestBody WechatLoginRequestDTO wechatLoginRequestDTO) throws URISyntaxException, IOException {
        String s = httpUtil.doPost(wechatLoginRequestDTO.getCode());
        JSONObject jsonObject = JSONObject.parseObject(s);
        String sessionKey = jsonObject.getString("session_key");
        String openid =jsonObject.getString("openid");
        //检查数据库中是否存在，存在则不保存,更新session_key
        //不在，则保存到数据库中
        String token = "token_QRCodeWriting_"+openid;
        WechatUser wechatUser = userService.getOpenIdWechat(openid);
        if(null == wechatUser)
        {
            wechatUser = new WechatUser();
            wechatUser.setOpenid(openid);
            wechatUser.setUsername("微信用户");
            wechatUser.setSessionKey(sessionKey);
            wechatUser.setToken(token);
            userService.save(wechatUser);
        }
        else
        {
            wechatUser.setSessionKey(sessionKey);
            userService.updateById(wechatUser);
        }
        //返回一个map
        Map<String,String> map = new HashMap<>();
        map.put("openId",token);
        map.put("session_key",sessionKey);
        return DataView.success(map);
    }

    @RequestMapping(value = "/checkLogin",method = RequestMethod.GET)
    public DataView checkLogin(@RequestParam String token)
    {
        System.out.println(token);
        DataView dataView = new DataView();
        if(token == null || token.equals(""))
        {
            dataView.setCode(2);
            return dataView;
        }
        WechatUser wechatUser = userService.queryToken(token);
        if(null==wechatUser)
        {
            dataView.setCode(1);
            return dataView;
        }
        dataView.setCode(0);
        return dataView;
    }
}
